package com.praveen.reminder;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

public class XMLFileManager {
	private DocumentBuilderFactory factory;
	private DocumentBuilder builder;
	private Document doc;
	private Element root;
	
	private void getFactoryBuilderAndFactory() {
		factory = DocumentBuilderFactory.newInstance();
		try {
			builder = factory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}
	
	public XMLFileManager() {
		getFactoryBuilderAndFactory();
		doc = builder.newDocument();
		root = doc.createElement("ReminderData");
		doc.appendChild(root);
	}
	
	public XMLFileManager(File file) {
		getFactoryBuilderAndFactory();
		try {
			doc = builder.parse(file);
			root = doc.getDocumentElement();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void appendNewDataNode(ReminderData data) {
		Element rElement = doc.createElement("Reminder");
		rElement.setAttribute("Text", data.getmReminderText());
		rElement.setAttribute("Entry", Integer.toString(data.getmEntryNo()));
		Element child = doc.createElement("Day");
		child.appendChild(doc.createTextNode(Utility.pad(data.getmDay())));
		rElement.appendChild(child);
		child = doc.createElement("Month");
		child.appendChild(doc.createTextNode(Utility.pad(data.getmMonth())));
		rElement.appendChild(child);
		child = doc.createElement("Year");
		child.appendChild(doc.createTextNode(Utility.pad(data.getmYear())));
		rElement.appendChild(child);
		child = doc.createElement("Hour");
		child.appendChild(doc.createTextNode(Utility.pad(data.getmHour())));
		rElement.appendChild(child);
		child = doc.createElement("Minute");
		child.appendChild(doc.createTextNode(Utility.pad(data.getmMinute())));
		rElement.appendChild(child);
		child = doc.createElement("Options");
		Element repeatOption = doc.createElement("RepeatInterval");
		repeatOption.appendChild(doc.createTextNode(Integer.toString(data.getmRepeatFreq())));
		child.appendChild(repeatOption);
		rElement.appendChild(child);
		root.appendChild(rElement);
	}
	
	public void deleteDataNode(Element e) {
		root.removeChild(e);
	}
	
	public Document getDocument() {
		return doc;
	}
}
